/**
 * Copyright © 2018 嘉源锐信. All rights reserved.
 *
 * @Title: MqLogServiceImpl.java
 * @Project: mq-consumer-client
 * @Package: com.huntkey.rx.sceo.mq.client.consumer.service.impl
 * @Description: TODO
 * @author: liuyong0
 * @date: 2018年9月19日 上午11:28:41
 * @version: V1.0
 */
package com.amos.mqclient.consumer.service.impl;

import com.amos.mqclient.consumer.service.MqLogService;
import com.amos.mqclient.pojo.MqMessage;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.dao.support.DataAccessUtils;
import org.springframework.jdbc.core.BeanPropertyRowMapper;
import org.springframework.jdbc.core.JdbcTemplate;
import org.springframework.stereotype.Service;
import org.springframework.util.StringUtils;

import javax.annotation.PostConstruct;
import javax.sql.DataSource;
import java.util.List;

/**
 * @ClassName: MqLogServiceImpl
 * @Description: TODO
 * @author: liuyong0
 * @date: 2018年9月19日 上午11:28:41  
 */
@Service
public class MqLogServiceImpl implements MqLogService {

    private static final Logger logger = LoggerFactory.getLogger(MqLogServiceImpl.class);

    @Autowired
    private DataSource mqLogDataSource;

    private JdbcTemplate jdbcTemplate;

    /**
     * @Title: init
     * @date: 2018年9月19日 上午11:32:45
     * @Description: bean加载后，实例化JdbcTemplate
     */
    @PostConstruct
    private void init() {
        this.jdbcTemplate = new JdbcTemplate();
        this.jdbcTemplate.setDataSource(mqLogDataSource);
    }

    /**
     * 更新消息表中消息状态
     * @param message
     * @param status
     */
    @Override
    public void updateMessageStatus(MqMessage message, String status) {
        logger.info("----- updateMessageStatus start -----");
        logger.info("message : {}, status : {} ", message.toString(), status);
        String selectSql = "select * from rabbitmq_message_trace where message_id=?";
        String updateSql = "update rabbitmq_message_trace set message_status = ? where message_id=?";
        if (null != message && !StringUtils.isEmpty(status)) {
            try {
                List<MqMessage> query = jdbcTemplate.query(selectSql, new BeanPropertyRowMapper<MqMessage>(MqMessage.class), message.getMessageId());
                MqMessage oldMessage = DataAccessUtils.uniqueResult(query);
                if (null != oldMessage) {
                    this.jdbcTemplate.update(updateSql, status, message.getMessageId());
                } else {
                    message.setMessageStatus(status);
                    String insertSql = "insert into rabbitmq_message_trace(message_id, exchange_type, exchange_name, route_key, message_body, message_status, try_num, cretime)" +
                            " values('" + message.getMessageId() + "','" + message.getExchangeType() + "','" + message.getExchangeName() + "','" + message.getRouteKey() + "','" +
                            message.getMessageBody() + "','" + status + "',0,NOW())";
                    this.jdbcTemplate.update(insertSql);
                }
            } catch (Exception e) {
                logger.error("维护消息状态时出错：" + e.getMessage());
            }
        } else {
            logger.error("维护消息状态时，状态参数不可以为空.");
        }
        logger.info("----- updateMessageStatus end -----");
    }

    /**
     * 更新错误信息
     * @param messageId
     */
    @Override
    public void updateMessageError(String messageId, String error_cause) {
        logger.info("----- updateMessageError start -----");
        logger.info("updateMessageError : messageId : {}, error_cause : {}", messageId, error_cause);
        String updateSql = "update rabbitmq_message_trace set receive_error = ? where message_id=?";
        if (!StringUtils.isEmpty(messageId) || !StringUtils.isEmpty(error_cause)) {
            this.jdbcTemplate.update(updateSql, error_cause, messageId);
        }
        logger.info("----- updateMessageError end -----");
    }

    /**
     * 根据消息id获取消息体内容
     * @param messageId
     * @return
     */
    @Override
    public MqMessage getMessageById(String messageId) {
        logger.info("getMessageById : messageId : {}", messageId);
        MqMessage msg = null;
        if (StringUtils.isEmpty(messageId)) {
            try {
                String selectSql = "select * from rabbitmq_message_trace where message_id=?";
                Object[] args = {messageId};
                msg = this.jdbcTemplate.queryForObject(selectSql, new BeanPropertyRowMapper<MqMessage>(MqMessage.class), args);
            } catch (Exception e) {
                logger.error("查询消息{}状态时，参数不可以为空.", messageId);
            }
        } else {
            logger.error("查询消息状态时，参数不可以为空.");
        }
        return msg;
    }

}
